<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="cateName" placeholder="请输入分类名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="categoryOptions" :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" ref="cateTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--列表数据-->
        <pane size="84">
          <el-col>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产编码" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入资产编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂商" prop="orgId">
        <el-select v-model="queryParams.orgId" placeholder="请选择厂商" clearable style="width:160px">
          <el-option
            v-for="u in orgOptions"
            :key="u.id"
            :label="u.name"
            :value="u.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="modelId">
        <el-select v-model="queryParams.modelId" placeholder="请选择型号" clearable style="width:160px">
          <el-option
            v-for="u in modelOptions"
            :key="u.id"
            :label="u.name"
            :value="u.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="houseId">
        <el-select v-model="queryParams.houseId" placeholder="请选择仓库" clearable style="width:160px">
          <el-option
            v-for="u in houseOptions"
            :key="u.id"
            :label="u.name"
            :value="u.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择资产状态" style="width: 160px" clearable>
          <el-option
            v-for="dict in asset_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否在库" prop="inStore">
        <el-select v-model="queryParams.inStore" placeholder="请选择是否在库" style="width: 160px" clearable>
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否在用" prop="isUse">
        <el-select v-model="queryParams.isUse" placeholder="请选择是否" style="width: 160px" clearable>
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" :data="deptOptions"  style="width: 240px"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly />
      </el-form-item>
      <el-form-item label="使用人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable  style="width: 160px">
            <el-option
              v-for="u in userOptions"
              :key="u.value"
              :label="u.label"
              :value="u.value"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="购买时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeBuyTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['asset:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['asset:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['asset:info:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['asset:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资产分类" align="center" prop="cateName" />
      <el-table-column label="资产编码" align="center" prop="num" />
      <el-table-column label="厂商" align="center" prop="orgName" />
      <el-table-column label="型号" align="center" prop="modelName" />
      <el-table-column label="当前价值" align="center" prop="price" />
      <el-table-column label="所在仓库" align="center" prop="houseName" />
      <el-table-column label="是否在库" align="center" prop="inStore">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.inStore"/>
        </template>
      </el-table-column>
      <el-table-column label="图例" align="center" prop="imgs" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="资产状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="asset_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否在用" align="center" prop="isUse">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isUse"/>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="使用人" align="center" prop="userName" />
      <el-table-column label="购买时间" align="center" prop="buyTime" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
        <template #default="scope">
          <el-button link type="primary" icon="Printer" @click="handlePrint(scope.row)">打印</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['asset:info:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['asset:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改资产信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="80px">
      <el-tabs v-model="tab">
      <el-tab-pane label="基本信息" name="base">
        <el-form-item label="资产分类" prop="cateId">
          <el-tree-select v-model="form.cateId" :data="categoryOptions" :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择分类" check-strictly />
        </el-form-item>
        <el-form-item label="资产编码" prop="num">
          <el-input v-model="form.num" placeholder="请输入资产编码" />
        </el-form-item>
        <el-form-item label="厂商" prop="orgId">
          <el-select v-model="form.orgId" placeholder="请选择厂商" clearable style="width:160px">
            <el-option
              v-for="u in orgOptions"
              :key="u.id"
              :label="u.name"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择型号" clearable style="width:160px">
            <el-option
              v-for="u in modelOptions"
              :key="u.id"
              :label="u.name"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="预留字段1" prop="num1">
          <el-input v-model="form.num1" placeholder="请输入预留字段1" />
        </el-form-item>
        <el-form-item label="预留字段2" prop="num2">
          <el-input v-model="form.num2" placeholder="请输入预留字段2" />
        </el-form-item>
        <el-form-item label="预留字段3" prop="text1">
          <el-input v-model="form.text1" placeholder="请输入预留字段3" />
        </el-form-item>
        <el-form-item label="预留字段4" prop="text2">
          <el-input v-model="form.text2" placeholder="请输入预留字段4" />
        </el-form-item>
        <el-form-item label="预留字段5" prop="file1">
          <el-input v-model="form.file1" placeholder="请输入预留字段5" />
        </el-form-item>
        <el-form-item label="预留字段6" prop="date1">
          <el-date-picker clearable
            v-model="form.date1"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预留字段6">
          </el-date-picker>
        </el-form-item>
        --->

        <el-form-item label="当前价值" prop="price">
          <el-input v-model="form.price" placeholder="请输入当前价值" />
        </el-form-item>
        <el-form-item label="仓库" prop="houseId">
          <el-select v-model="form.houseId" placeholder="请选择仓库" clearable style="width:160px">
            <el-option
              v-for="u in houseOptions"
              :key="u.id"
              :label="u.name"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否在库" prop="inStore">
          <el-radio-group v-model="form.inStore">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资产状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择资产状态" style="width: 160px">
            <el-option
              v-for="dict in asset_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly />
        </el-form-item>
        <el-form-item label="是否在用" prop="isUse">
          <el-radio-group v-model="form.isUse">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用人" prop="userId" v-if="form.isUse == 'Y'">
          <el-select v-model="form.userId" placeholder="请选择用户" clearable style="width: 160px">
              <el-option
                v-for="u in userOptions"
                :key="u.value"
                :label="u.label"
                :value="u.value"
              />
            </el-select>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="详细信息" name="detail">
        <el-form-item label="图例" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
        <el-form-item label="资产说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入资产说明" />
        </el-form-item>
        <el-form-item label="购买时间" prop="buyTime">
          <el-date-picker clearable
            v-model="form.buyTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择购买时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报废时间" prop="scrapTime">
          <el-date-picker clearable
            v-model="form.scrapTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择报废时间">
          </el-date-picker>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="二维码" name="qr" v-if="form.num">
        <el-form-item label="图例" prop="imgs">
          <img :width="qrSize" :height="qrSzie" :src="assetQrImg(form)" />
        </el-form-item>
      </el-tab-pane>
      </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Info">
import { getToken } from "@/utils/auth";
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/asset/info";
import { selectCategory } from "@/api/base/category";
import useAppStore from '@/store/modules/app'
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { queryDs } from "@/api/dev/dataset";
import { selectWarehouse } from "@/api/base/warehouse";
import { selectOrganization } from "@/api/base/organization";
import { selectModel } from "@/api/base/model";

const { proxy } = getCurrentInstance();
const appStore = useAppStore()
const { asset_status, sys_yes_no } = proxy.useDict('asset_status', 'sys_yes_no');

const infoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tab = ref("base");
const title = ref("");
const daterangeBuyTime = ref([]);
const cateName = ref(null);
const categoryOptions = ref([]);
const houseOptions = ref([]);
const userOptions = ref([]);
const orgOptions = ref([]);
const modelOptions = ref([]);
const deptOptions = ref([]);

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/asset/info/importData"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'DESC',
    cateId: null,
    num: null,
    orgId: null,
    modelId: null,
    houseId: null,
    status: null,
    inStore: null,
    isUse: null,
    deptId: null,
    userId: null,
    buyTime: null,
  },
  rules: {
    cateId: [
      { required: true, message: "资产分类不能为空", trigger: "blur" }
    ],
    num: [
      { required: true, message: "资产编码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资产信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeBuyTime && '' != daterangeBuyTime) {
    queryParams.value.params["beginBuyTime"] = daterangeBuyTime.value[0];
    queryParams.value.params["endBuyTime"] = daterangeBuyTime.value[1];
  }
  listInfo(queryParams.value).then(response => {
    infoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.cateId = data.id;
  handleQuery();
};

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(cateName, val => {
  proxy.$refs["cateTreeRef"].filter(val);
});

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    cateId: queryParams.value.cateId,
    num: null,
    orgId: null,
    modelId: null,
    num1: null,
    num2: null,
    text1: null,
    text2: null,
    file1: null,
    date1: null,
    price: null,
    houseId: null,
    imgs: null,
    remark: null,
    status: '1',
    inStore: 'Y',
    isUse: 'N',
    deptId: null,
    userId: null,
    scrapTime: null,
    buyTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    createTime: null
  };
  proxy.resetForm("infoRef");
  tab.value = 'base';
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeBuyTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资产信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资产信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if(form.value.isUse == 'N'){
        form.value.userId = null;
      }
      if (form.value.id != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的资产信息,请确认这些资产已经不再有效且工单流程已经完成？').then(function() {
    return delInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('asset/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "资产信息导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("asset/info/importTemplate", {
  }, `asset_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 二维码 */
function assetQrImg(row){
  return import.meta.env.VITE_APP_BASE_API + "/asset/qr/img/"+row.id
}

/** 打印 */
function handlePrint(row) {
  console.log(location.origin + import.meta.env.VITE_APP_BASE_API + "/asset/qr/print/"+row.id);
  const printWindow = window.open(location.origin + import.meta.env.VITE_APP_BASE_API + "/asset/qr/print/"+row.id, '_blank');
  //printWindow.focus();
  printWindow.print();
  //printWindow.close();
}


getList();

selectCategory().then(response => {
  categoryOptions.value = [];
  const data = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy.handleTree(response.data, "id", "pid");
  categoryOptions.value.push(data);
});

selectWarehouse({}).then(response=>{
    houseOptions.value = response.data;
});
selectOrganization({}).then(response=>{
    orgOptions.value = response.data;
});
selectModel({}).then(response=>{
    modelOptions.value = response.data;
});
queryDs({"code":"sys_user_select"}).then(response=>{
    userOptions.value = response.data;
});
queryDs({"code":"sys_dept_tree"}).then(response=>{
  deptOptions.value = proxy.handleTree(response.data, "id", "pid");
});
</script>
